/*******************************************************************************
 * Copyright 2011 Towee.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package net.towee.server.rpc.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.towee.server.CoreSettings;
import net.towee.server.gxp.AuthenticationPage;

import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.inject.name.Named;

public class AuthenticationServlet extends HttpServlet {

	private final String domain;
	private final int port;

	/**
	 * Creates a servlet for the wave client.
	 */
	@Inject
	public AuthenticationServlet(
			@Named(CoreSettings.TOWEE_SERVER_DOMAIN) String domain,
			@Named(CoreSettings.TOWEE_SERVER_PORT) int port) {

		this.domain = domain;
		this.port = port;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse response)
			throws IOException {
		if (req.getRequestURL().indexOf("http://"+domain) != 0)
			response.sendRedirect("http://"+domain+( (port!=80)?":"+port:"" ));
		else {
			// Disable any page caching
			response.setHeader("Expires", new Date().toString());
			response.setHeader("Last-Modified", new Date().toString());
			response.setHeader("Cache-Control",
					"no-store, no-cache, must-revalidate, max-age=0");
			response.setHeader("Pragma", "no-cache");
			
			// Show page
			AuthenticationPage.write(response.getWriter(), new GxpContext(req.getLocale()));
		}
	}
}
